package com.hua.yuan.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.hua.yuan.R;
import com.hua.yuan.base.Constents;
import com.hua.yuan.common.BaseActivity;
import com.hua.yuan.ui.module.ImageDetail;
import com.hua.yuan.util.DensityUtil;

import java.util.List;

import cm.hua.yuan.common.utils.PreferenceUtils;

/**
 * Created by huangyang on 2018/7/22.
 * 图集的详情页
 */

public class ImageDetailBrowActivity extends BaseActivity implements AdapterView.OnItemSelectedListener, View.OnClickListener {

    private ImageView backImage;
    private TextView titleView;

    private ScrollView sv_layout;
    private ImageView iv_cover;
    private TextView iv_atlas_desc;
    private TextView tv_sees;
    private TextView iv_detail;
    private ImageAdapter adapter;
    private ImageView iv_toleft;
    private ImageView iv_toright;

    private RelativeLayout buyRlView;
    private TextView videoNameShow;
    private TextView videoBuyMoney;
    private TextView videoKaiTongVip;
    private TextView videoCancelTv;
    private Gallery gallery;
    private ImageView iv_close_brow;

    private ImageDetail imageDetail;
    private List<ImageDetail.PicturesListBean> pictures_list;
    private int spacing = 0;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image_detail_brow);
        imageDetail = getIntent().getParcelableExtra("imageDetail");
        initView();
    }

    private void initView() {
        backImage = findViewById(R.id.backImage);
        titleView = findViewById(R.id.titleView);
        backImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        sv_layout = findViewById(R.id.sv_layout);
        iv_cover = findViewById(R.id.iv_cover);
        iv_atlas_desc = findViewById(R.id.iv_atlas_desc);
        tv_sees = findViewById(R.id.tv_sees);
        iv_detail = findViewById(R.id.iv_detail);
        iv_toleft = findViewById(R.id.iv_toleft);
        iv_toright = findViewById(R.id.iv_toright);

        buyRlView = findViewById(R.id.buyRlView);
        videoNameShow = findViewById(R.id.videoNameShow);
        videoBuyMoney = findViewById(R.id.videoBuyMoney);
        videoKaiTongVip = findViewById(R.id.videoKaiTongVip);
        videoCancelTv = findViewById(R.id.videoCancelTv);
        videoNameShow.setOnClickListener(this);
        videoBuyMoney.setOnClickListener(this);
        videoKaiTongVip.setOnClickListener(this);
        videoCancelTv.setOnClickListener(this);
        iv_toleft.setOnClickListener(this);
        iv_toright.setOnClickListener(this);
        iv_cover.setOnClickListener(this);
        iv_close_brow = findViewById(R.id.iv_close_brow);
        iv_close_brow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        receiver = new MyBroadcastReceiver();
        myRegister();

        setData(imageDetail);
    }

    private void setData(final ImageDetail imageDetail) {
        //封面
        Glide.with(ImageDetailBrowActivity.this)
                .load(imageDetail.getImg_url())
                .into(iv_cover);

        titleView.setText(imageDetail.getTitle());
        iv_atlas_desc.setText(imageDetail.getTitle());
        tv_sees.setText(imageDetail.getPlay_num());
        iv_detail.setText(imageDetail.getAtlas_desc());

        videoNameShow.setText("您还未购买本图集");
        videoBuyMoney.setText(imageDetail.getNow_price() + "代币购买本图集");
        videoKaiTongVip.setText("开通会员免费看");
        videoCancelTv.setText("取消");

        pictures_list = imageDetail.getPictures_list();

        spacing = DensityUtil.dip2px(ImageDetailBrowActivity.this, 15);
        gallery = (Gallery) findViewById(R.id.gallery);
        adapter = new ImageAdapter(this);
        gallery.setAdapter(adapter);
        gallery.setSpacing(spacing);
        gallery.setOnItemSelectedListener(this);

        iv_cover.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (imageDetail != null) {
                    if ("0".equals(imageDetail.getIs_free())) {
                        if ("0".equals(imageDetail.getHas_buy())) {
                            buyRlView.setVisibility(View.VISIBLE);
                        }else{
                            Intent intent = new Intent(ImageDetailBrowActivity.this, ImageBigActivity.class);
                            intent.putExtra("imageDetail", imageDetail);
                            intent.putExtra("position", position);
                            startActivity(intent);
                        }
                    }else{
                        Intent intent = new Intent(ImageDetailBrowActivity.this, ImageBigActivity.class);
                        intent.putExtra("imageDetail", imageDetail);
                        intent.putExtra("position", position);
                        startActivity(intent);
                    }
                }
            }
        });
    }

    int position = 0;
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        if (imageDetail != null) {
            if ("0".equals(imageDetail.getIs_free())) {
                if ("0".equals(imageDetail.getHas_buy())) {
                    buyRlView.setVisibility(View.VISIBLE);
                }
            }
        }
        this.position = position;
        adapter.setSelectItem(position);  //当滑动时，事件响应，调用适配器中的这个方法。
        Glide.with(ImageDetailBrowActivity.this)
                .load(imageDetail.getPictures_list().get(position).getImg_url())
                .into(iv_cover);

        Log.d("TAG", "pos:"+position);
    }

    @Override
    public void onNothingSelected(AdapterView<?> arg0) {//抽象方法，必须实现
        // TODO Auto-generated method stub
    }


    private void myRegister() {
        if (receiver != null) {
            IntentFilter filter = new IntentFilter();
            filter.addAction("go_to_buy");
            filter.addAction("delete_con_success");
            registerReceiver(receiver, filter);
        }
    }

    private class MyBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if ("delete_con_success".equals(action)) {
                if (imageDetail != null) {
                    imageDetail.setHas_buy("1");
                }
            }
        }
    }
    private MyBroadcastReceiver receiver;
    private void myUnRegister() {
        if (receiver != null) {
            unregisterReceiver(receiver);
            receiver = null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        myUnRegister();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.videoBuyMoney://10元代币购买本图集
                //买
                goActivity();
                buyRlView.setVisibility(View.GONE);
                break;
            case R.id.videoKaiTongVip://开通会员免费看
                //开通
                buyRlView.setVisibility(View.GONE);
                break;
            case R.id.videoCancelTv://取消
                buyRlView.setVisibility(View.GONE);
                break;
            case R.id.iv_toleft:
                //如果在代码调用了gallery.setSpacing(2)；这样的设置，会使prePage和nextPage中的onKeyDown失效。
                //如果想保留gallery.setSpacing( SPACING )
                gallery.onScroll(null, null, -1 * spacing, 0);
                gallery.onKeyDown(KeyEvent.KEYCODE_DPAD_LEFT, null);
                break;
            case R.id.iv_toright:
                gallery.onScroll(null, null, spacing, 0);
                gallery.onKeyDown(KeyEvent.KEYCODE_DPAD_RIGHT, null);
                break;
        }
    }

    private void goActivity() {

        boolean flag = PreferenceUtils.getBoolean(Constents.IS_LOGIN);
        if (flag) {
            //登录了直接跳转

            if (imageDetail != null) {
                String money = imageDetail.getNow_price();
                String id = imageDetail.getAtlas_id() + "";

                Intent intent = new Intent(ImageDetailBrowActivity.this, MoneyBagActivity.class);
                intent.putExtra("buyMoney", money);
                intent.putExtra("movieId", id);
                intent.putExtra("isTuji", true);
                startActivity(intent);
//                finish();
            }


        } else {
            //没有登录 先登录
            startActivity(new Intent(this, LoginActivity.class));
        }
    }

    public class ImageAdapter extends BaseAdapter {
        private Context mContext;
        private int selectItem;

        public ImageAdapter(Context mContext) {
            this.mContext = mContext;
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
//            return Integer.MAX_VALUE;          //这里的目的是可以让图片循环浏览
            return pictures_list.size();          //这里的目的是可以让图片循环浏览
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        public void setSelectItem(int selectItem) {
            if (this.selectItem != selectItem) {
                this.selectItem = selectItem;
                notifyDataSetChanged();
            }
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            ImageView imageView = new ImageView(mContext);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            Glide.with(ImageDetailBrowActivity.this)
                    .load(pictures_list.get(position).getImg_url())
                    .into(imageView);

            if (selectItem == position) {
                Animation animation = AnimationUtils.loadAnimation(mContext, R.anim.gallery_select_anim);    //实现动画效果
                imageView.setLayoutParams(new Gallery.LayoutParams(DensityUtil.dip2px(ImageDetailBrowActivity.this, 65), DensityUtil.dip2px(ImageDetailBrowActivity.this, 90)));
                imageView.startAnimation(animation);  //选中时，这是设置的比较大
            } else {
                imageView.setLayoutParams(new Gallery.LayoutParams(DensityUtil.dip2px(ImageDetailBrowActivity.this, 55), DensityUtil.dip2px(ImageDetailBrowActivity.this, 80)));
                //未选中
            }
            return imageView;
        }
    }


    public boolean isLogin() {
        boolean flag = PreferenceUtils.getBoolean(Constents.IS_LOGIN);
        if (!flag) {
            //没有登录 先登录
            startActivity(new Intent(this, LoginActivity.class));
        }
        return flag;
    }

}
